<script setup>
import { useApi } from "../../composables/useApi.js";
import showTost from "@/components/toast/index.js";
import { storeToRefs } from "pinia";
import { useAppStore } from "../../store/app.js";

const appStore = useAppStore();

const { nationArr, sexArr } = storeToRefs(appStore);
import { reactive, ref } from "vue";
import StandardGradeDrawear from "@/pages/platform/components/standardGradeDrawear.vue";
import { router } from "@/plugins/1.router/index.js";
import * as XLSX from "xlsx";
import { getStudentList } from "@/api/student.js";
import { standardAddModify, standardDelete } from "@/api/standard.js";
import ModelHeader from "@/pages/platform/components/modelHeader.vue";
import UploadOhterImg from "@/components/uploadOhterImg.vue";
import {
  medalAddModify,
  medalDelete,
  medalRecordAddModify,
  medalRecordDelete,
} from "@/api/medal.js";
import MedalDrawear from "@/pages/platform/components/medalDrawear.vue";
import communitySecondDrawear from "@/pages/platform/components/communitySecondDrawear.vue";
import PacketStaffSecondDrawear from "@/pages/platform/components/packetStaffSecondDrawear.vue";

let route = useRoute();

//基本数据list
let list = ref([]);
let page = ref(1);
let limit = ref(20);
let total = ref(0); //总数
const selected = ref([]);
let queryFrom = ref({ page: 1, limit: 20, studentName: "" });

const headers = [
  {
    title: "学生姓名",
    key: "studentName",
    width: "240px",
    align: "start",
  },
  {
    title: "学生ID",
    width: "240px",
    align: "start",
    key: "studentId",
  },
  {
    title: "获得分数",
    width: "240px",
    align: "start",
    key: "score",
  },
  {
    title: "完成时间",
    width: "240px",
    align: "start",
    key: "successTime",
  },
  {
    title: "操作",
    align: "end",
    width: "240px",
    sortable: false,
    key: "options",
  },
];

const headersRecord = [
  {
    title: "教师姓名",
    key: "teacherName",
    width: "240px",
    align: "start",
  },
  {
    title: "教师ID",
    width: "240px",
    align: "start",
    key: "teacher_id",
  },
  {
    title: "教师职位描述",
    width: "240px",
    align: "start",
    key: "content",
  },
  {
    title: "操作",
    align: "end",
    width: "240px",
    sortable: false,
    key: "options",
  },
];
const tabsIndex = ref(0);

const examcourse_id = ref(null);
// todo 复制修改列表接口
const getList = async () => {
  const { data } = await useApi("/teacher/Api.JobRecord/index").post({
    ...queryFrom.value,
    job_id: route.query.job_id,
  });
  total.value = data.value.data.total;
  list.value = data.value.data.data.map((item) => {
    return {
      ...item, id: tabsIndex.value === 0 ? item.jobrecord_id : item.teacher_id,
    }
  })
  console.log(list.value)
}
getList()
const dialogFlag = ref(false)
// 头部表单回调
const onChange = (val) => {
  let data = JSON.parse(JSON.stringify(val));
  queryFrom.value = { ...queryFrom.value, ...data };
  getList();
};
const isConfirmDialogVisible = ref(false);
// 删除确认弹窗
const onHandleDelete = async (val) => {
  console.log(val);
  if (tabsIndex.value == 0) {
    let ids = val.data.map((item) => item.jobrecord_id).toString();
    console.log(ids);
    const { data } = await useApi("/teacher/Api.JobRecord/delete").post({
      jobrecord_id: ids,
    });
    console.log(data.value);
    if (data.value.status == 200) {
      showTost("删除成功", { duration: 3000, type: "success" });
      queryFrom.value.page = 1;
      isConfirmDialogVisible.value = false;
      if (val.type == "detail") {
        dialogFlag.value = false;
      }
      getList();
    }
  } else {
    let ids = val.data.map((item) => item.jobrecord_id).toString();
    console.log(ids);
    const { data } = await useApi("/teacher/Api.JobRecord/delete").post({
      jobrecord_id: ids,
    });
    console.log(data.value);
    if (data.value.status == 200) {
      showTost("删除成功", { duration: 3000, type: "success" });
      queryFrom.value.page = 1;
      isConfirmDialogVisible.value = false;
      if (val.type == "detail") {
        dialogFlag.value = false;
      }
      getList();
    }
  }
};
const selectedItems = ref([]);

// 确认弹窗文本
const confirmMsg = ref("");
const currentOptionData = ref({});

// 打开删除弹窗
const onHandleDialog = (type) => {
  if (type == "delete") {
    console.log(selectedItems);
    if (selectedItems.value.length == 0) return;
    let data = list.value.filter((item) =>
      selectedItems.value.find((val) => val == item.id)
    );
    console.log(data);
    currentOptionData.value = {
      data: data,
      type: "list",
    };
    console.log(data);
    confirmMsg.value = `确认删除${
      tabsIndex.value == 0
        ? data.map((item) => item.studentName).toString()
        : data.map((item) => item.teacherName).toString()
    }的信息吗?`;
    isConfirmDialogVisible.value = true;
  } else if (type == "openSecondPage") {
    router.push("/platform/times-manage?type=2");
  } else {
    addDialogFlag.value = true;
  }
};
// 详情数据
const detailData = ref({});

// 去详情
const viewDetail = async (item) => {
  console.log(item);
  const { data } = await useApi(
    tabsIndex.value == 0
      ? "\n" + "/teacher/Api.JobRecord/detail"
      : "/teacher/Api.GroupTeacher/detail"
  ).post({
    jobrecord_id: item.jobrecord_id,
  })
  console.log(data)
  detailData.value = data.value.data
  console.log()
  dialogFlag.value = true
}
// 添加教师弹窗falg
const addDialogFlag = ref(false);
const refVForm = ref();

// 下载模板
const downLoadTemplate = async () => {
  const { data } = await useApi("/teacher/Base/downFile").post({ type: 5 });
  console.log(data.value);
  if (data.value.status == 200) {
    const link = document.createElement("a");
    link.href = data.value.data.fileUrl;
    link.download = data.value.data.fileName;
    link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click();
  }
};
// 新增取消回调
const resetForm = () => {
  refVForm.value?.reset();
  addDialogFlag.value = false;
};

const valid = ref(false);
const form = reactive({
  class_id: null,
  grade_id: null,
  studentId: null,
  successTime: null,
  remark: "",
});

let totalScore = computed(() => {
  return (
    Number(form.languageScore) +
    Number(form.mathsScore) +
    Number(form.englishScore)
  );
});

const confirmAdd = async (args) => {
  console.log(totalScore.value);
  if (!valid.value) return;
  if (tabsIndex.value == 0) {
    const { data } = await useApi("/teacher/Api.JobRecord/add").post({
      ...form,
      job_id: route.query.job_id,
    });
    if (data.value.status == 200) {
      refVForm.value?.reset();
      addDialogFlag.value = false;
      showTost("新增成功", { duration: 3000, type: "success" });
      queryFrom.value.page = 1;
      getList();
    } else {
      console.log(data.value.msg);
      // showTost("新增成功", {duration: 3000, type: "success"})

      showTost(data.value.msg, { duration: 3000, type: "error" });
    }
  } else {
    const { data } = await useApi("/teacher/Api.GroupTeacher/add").post({
      ...form,
      group_id: route.query.id,
    });
    if (data.value.status == 200) {
      refVForm.value?.reset();
      addDialogFlag.value = false;
      showTost("新增成功", { duration: 3000, type: "success" });
      queryFrom.value.page = 1;
      getList();
    }
  }
};
let sexList = ref(["男", "女"]);
const onHandleEdit = () => {
  queryFrom.value.page = 1;
  getList();
};
// getList()
const required = (value, name) => !!value || `${name}为必填字段`;

const import_page = ref(1);
const import_limit = ref(10);
const import_percent = ref(0);
const loading = ref(false);

const partPost = async (tableData) => {
  let perdata = [];
  for (
    let i = (import_page.value - 1) * import_limit.value;
    i < import_page.value * import_limit.value;
    i++
  ) {
    if (tableData[i]) {
      perdata.push(tableData[i]);
    }
  }
  let total_page = Math.ceil(tableData.length / import_limit.value);
  import_percent.value = Math.ceil((import_page.value * 100) / total_page);
  loading.value = true;
  console.log(perdata);
  const { data } = await useApi("/teacher/Api.Standardization/upload").post(
    JSON.stringify(perdata)
  );
  if (data.value.status == 200) {
    if (import_page.value <= total_page - 1) {
      import_page.value = import_page.value + 1;
      partPost(data);
    } else {
      // this.dialog.importDialogstatus = false;
      showTost("导入完成", { duration: 3000, type: "success" });
      loading.value = false;
    }
  }
};

const onChangePage = (val) => {
  queryFrom.value.page = val.page;
  queryFrom.value.limit = val.limit;
  getList();
};
const drawaerDelete = async (val) => {
  console.log(val);
  currentOptionData.value = {
    data: [val],
    type: "detail",
  };
  confirmMsg.value = `确认删除${val.studentName}的信息吗`;
  isConfirmDialogVisible.value = true;
};
const viewDetailClassStudent = (type, item) => {
  showTost("暂未开放");
  if (type == "class") {
  }
};
// 二级页面显示开关
const secondPageShowFlag = ref(false);
const onHandleSecondPage = () => {
  secondPageShowFlag.value = true;
};
const examTitle = ref("");
const changeId = (val) => {
  examcourse_id.value = val.id;
  examTitle.value = val.title;
  getList();
};
const httpRequest = (e) => {
  let file = e.file; // 文件信息
  if (!file) {
    return false;
  } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    // 格式根据自己需求定义
    this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
    return false;
  }
  const fileReader = new FileReader();
  fileReader.onload = (ev) => {
    try {
      const data = ev.target.result;
      const workbook = XLSX.read(data, {
        // 以字符编码的方式解析
        type: "binary",
        cellDates: true,
      });
      // 取第一张表
      console.log(workbook);
      const exlname = workbook.SheetNames[0];
      const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]); // 生成json表格内容
      console.log(exl);
      partPost(exl);
      // 将 JSON 数据挂到 data 里
      let arr = [];
      exl.forEach((item) => {
        arr.push(item.name);
      });
      console.log(arr);
    } catch (e) {
      console.log("error");
      return false;
    }
  };
  fileReader.readAsBinaryString(file);
};

const onlyAllowNumbers = (event) => {
  const key = event.key;
  // 检查按键是否为数字或控制键（如 backspace）
  if (!/^\d$/.test(key) && event.key !== "Backspace" && event.key !== "Tab") {
    event.preventDefault();
  }
};
const filterInput = (key) => {
  // 仅保留数字
  form[key] = form[key].replace(/\D/g, "");
};

const projectList = ref(["德", "智", "体", "美", "劳"]);

const tabsChange = (index) => {
  tabsIndex.value = index;
  list.value = [];
  queryFrom.value.page = 1;
  getList();
};
/**  获取学生列表*/
const studentList = ref([]);
const getStudentListProp = async () => {
  const { data } = await useApi("/teacher/Api.StudentList/index").post({
    mass_id: route.query.mass_id,
    cateType: route.query.cateType,
  });
  if (data.value.status == 200) {
    studentList.value = data.value.data.data;
    console.log(studentList.value);
  }
};
getStudentListProp();

// 获取教师列表开始
const teacherList = ref([]);
const getTeacherList = async () => {
  const { data } = await useApi("/teacher/Api.Teacher/indexList").post({});
  if (data.value.status == 200) {
    teacherList.value = data.value.data;
  }
};
getTeacherList();
// 获取教师列表结束

/** 顶部切换素质教育/标化成绩tabs功能开始*/

const handleHeaderTabs = (index) => {
  tabsIndex.value = index;
  console.log(tabsIndex.value);
  //   todo tabs切换数据
  queryFrom.value.page = 1;
  getList();
};
/** 顶部切换素质教育/标化成绩tabs功能结束*/
// 获取年级列表开始
const gradeList = ref([]);
const getGradeList = async () => {
  const { data } = await useApi("/teacher/Api.Grade/indexList").post({});
  if (data.value.status == 200) {
    console.log(data.value.data);
    gradeList.value = data.value.data;
  }
};
getGradeList();
// 获取年级列表结束
// 班级不分页列表开始
const classList = ref([]);
const getClassList = async (id = "") => {
  const { data } = await useApi("/teacher/Api.GradeClass/indexList").post({
    grade_id: id,
  });
  if (data.value.status == 200) {
    console.log(data.value.data);
    classList.value = data.value.data;
  }
};
getClassList();
// 班级不分页列表结束
const gradeChange = (id) => {
  if (id != form.class_id) {
    form.class_id = "";
  }
  getClassList(id);
};

const classChange = (id) => {
  form.studentId = null;
  getStudentListProp();
};

const studentChange = (val) => {
  console.log(val);
  let data = studentList.value.find((item) => {
    return item.student_id == val;
  });
  form.class_id = data.class_id;
  form.grade_id = data.grade_id;
};
const isEdit = ref(false);
const onHandleEditData = async () => {
  if (isEdit.value === true) {

    console.log({ ...detailData.value,studentId:detailData.value.student_id })
    const {data} = await useApi('/teacher/Api.JobRecord/add').post({ ...detailData.value,studentId:detailData.value.student_id })
    if (data.value.status == 200) {
      // refVForm.value?.reset()
      showTost("修改成功", { duration: 3000, type: "success" });
      queryFrom.value.page = 1;
      getList();
      dialogFlag.value = false;
      isEdit.value = false;
    } else {
      console.log(data.value.msg);
      showTost(data.value.msg, { duration: 3000, type: "error" });
    }
  } else {
    isEdit.value = true;
  }
};
const closeDarwear = () => {
  refVForm.value?.reset();
};
const showFlag = ref(false);
const changeShowFlag = () => {
  showFlag.value = !showFlag.value;
};

const search = () => {
  getList();
};
</script>

<template>
  <div class="content">
    <!--   Ought to 修改右侧抽屉-->
    <custom-drawear
      :teacher-list="teacherList"
      @onHandleDelete="drawaerDelete"
      @onHandleEdit="onHandleEdit"
      :detailData="detailData"
      @update:isDrawerOpen="dialogFlag = $event"
      @close="closeDarwear"
      :is-drawer-open="dialogFlag"
    >
      <VForm :disabled="!isEdit" ref="refVForm1">
        <VRow>
          <VCol cols="6">
            <VTextField
              v-model="detailData.student_id"
              disabled
              label="学生ID"
              :rules="[(val) => required(val, '学生ID')]"
            >
              <template v-slot:label>
                <span>学生ID</span>
                <span style="color: red; margin-left: 4px">*</span>
              </template>
            </VTextField>
          </VCol>
          <VCol cols="6">
            <VAutocomplete
              v-model="detailData.student_id"
              @update:modelValue="studentChange"
              :items="studentList"
              item-title="studentName"
              item-value="studentId"
              :rules="[(val)=>required(val,'学生姓名')]"
              class="input-width-height"
            >
              <template v-slot:label>
                <span>学生姓名</span>
                <span style="color: red; margin-left: 4px">*</span>
              </template>
            </VAutocomplete>
          </VCol>

          <VCol cols="6">
            <VTextField
              v-model="detailData.score"
              label="分数"
              :rules="[(val) => required(val, '分数')]"
            >
              <template v-slot:label>
                <span>分数</span>
                <span style="color: red; margin-left: 4px">*</span>
              </template>
            </VTextField>
          </VCol>
          <VCol cols="6">
            <AppDateTimePicker
              class="input-width-height"
              v-model="detailData.successTime"
              label="完成时间"
              placeholder="请选择完成时间"
              :rules="[(val)=>required(val,'完成时间')]"
            >
              <template v-slot:label>
                <span>完成时间</span>
                <span style="color: red;margin-left: 4px;">*</span>
              </template>
            </AppDateTimePicker>
          </VCol>
        </VRow>
      </VForm>
      <div class="d-flex justify-end" style="height: 60px; margin-top: auto">
        <VBtn color="primary" class="me-4" @click="onHandleEditData">
          {{ isEdit == true ? "保存" : "编辑" }}
        </VBtn>
        <VBtn
          color="error"
          variant="outlined"
          @click="drawaerDelete(detailData)"
        >
          删除
        </VBtn>
      </div>
    </custom-drawear>
    <ConfirmDialog
      :handleData="currentOptionData"
      v-model:isDialogVisible="isConfirmDialogVisible"
      @confirm="onHandleDelete"
      :confirm-msg="confirmMsg"
      :confirmation-question="confirmMsg"
      cancel-msg="Unsubscription Cancelled!!"
    />
    <!--    Ought to 修改顶部检索栏部分-->
    <!-- 头部 -->
    <custom-header
      :title="route.query.name"
      :button-text="tabsIndex == 1 ? '添加职员' : '添加记录'"
      showBack="true"
      @tabsChange="tabsChange"
      @onChange="onChange"
      @changeId="changeId"
      @onHandle="onHandleDialog"
    >
            <template v-slot:select>
              <IconBtn size="small" style="position: relative">
                <i
                  class="ri-filter-3-line cursor-pointer"
                  style="block-size: 24px;inline-size: 24px;"
                  @click="changeShowFlag"
                />
              </IconBtn>
              <div class="menu-box" v-if="showFlag">
                <VList style="width: 310px!important;">
                  <VListItem style="width: 100%">
                    <template #prepend>
                      <VTextField
                        class="input-width-height"
                        v-model="queryFrom.studentName"
                        label="学生姓名"
                      >
                        <template v-slot:label>
                          <span>学生姓名</span>
                        </template>
                      </VTextField>
                    </template>
                  </VListItem>
                  <VListItem style="display: flex;justify-content: end">
                    <VBtn
                      color="primary"
                      class="me-4"
                      @click="search"
                    >
                      搜索
                    </VBtn>
                    <VBtn
                      type="submit"
                      color="primary"
                      @click="reset"
                    >
                      重置
                    </VBtn>
                  </VListItem>
                </VList>
              </div>

            </template>
    </custom-header>
    <VDataTable
      v-model="selectedItems"
      :headers="tabsIndex == 0 ? headers : headersRecord"
      :items-per-page="100"
      :items="list"
      item-key="id"
      show-select
      class="text-no-wrap"
    >
      <template #item.options="{ item }">
        <div class="d-flex align-center options-right-display">
          <div class="d-flex flex-column ms-3 cursor-pointer">
            <i @click="viewDetail(item)" class="ri-edit-line"></i>
          </div>
        </div>
      </template>
    </VDataTable>
    <PaginationVue
      @onChange="onChangePage"
      :current-page="queryFrom.page"
      :page-size="queryFrom.limit"
      :total="total"
    />
    <!--    添加对话框-->
    <VDialog :persistent="true" max-width="600" :model-value="addDialogFlag">
      <VDivider />
      <VCard>
        <AppDrawerHeaderSection
          :title="tabsIndex === 0 ? '添加学生' : '添加职员'"
          @cancel="addDialogFlag = false"
        />
        <PerfectScrollbar :options="{ wheelPropagation: false }" class="h-60">
          <VCardText>
            <VForm v-model="valid" ref="refVForm" @submit.prevent="confirmAdd">
              <VRow v-if="tabsIndex == 0">
                <VCol cols="6">
                  <VTextField
                    v-model="form.studentId"
                    disabled
                    label="学生ID"
                    :rules="[(val) => required(val, '学生ID')]"
                  >
                    <template v-slot:label>
                      <span>学生ID</span>
                      <span style="color: red; margin-left: 4px">*</span>
                    </template>
                  </VTextField>
                </VCol>
                <VCol cols="6">
                  <VAutocomplete
                    v-model="form.studentId"
                    @update:modelValue="studentChange"
                    :items="studentList"
                    item-title="studentName"
                    item-value="student_id"
                    :rules="[(val) => required(val, '学生姓名')]"
                    class="input-width-height"
                  >
                    <template v-slot:label>
                      <span>学生姓名</span>
                      <span style="color: red; margin-left: 4px">*</span>
                    </template>
                  </VAutocomplete>
                </VCol>
    
                <VCol cols="6">
                  <VTextField
                    v-model="form.score"
                    label="分数"
                    :rules="[(val) => required(val, '分数')]"
                  >
                    <template v-slot:label>
                      <span>分数</span>
                      <span style="color: red; margin-left: 4px">*</span>
                    </template>
                  </VTextField>
                </VCol>
                <VCol cols="6">
                  <AppDateTimePicker
                    class="input-width-height"
                    v-model="form.successTime"
                    label="获得时间"
                    placeholder="请选择获得时间"
                    :rules="[(val)=>required(val,'获得时间')]"
                  >
                    <template v-slot:label>
                      <span>获得时间</span>
                      <span style="color: red;margin-left: 4px;">*</span>
                    </template>
                  </AppDateTimePicker>
                </VCol>
                <VDivider style="margin-top: 20px" />
                <VCol cols="12">
                  <div class="d-flex justify-end">
                    <VBtn
                      color="secondary"
                      type="reset"
                      variant="tonal"
                      class="me-4"
                      @click="addDialogFlag = false"
                    >
                      取消
                    </VBtn>
                    <VBtn type="submit" color="primary" class="me-4">
                      确认
                    </VBtn>
                  </div>
                </VCol>
              </VRow>
            </VForm>
          </VCardText>
        </PerfectScrollbar>
      </VCard>
    </VDialog>
  </div>
</template>

<style lang="scss" scoped>
.back {
  margin-left: 10px;
}
.input-width-height {
  width: 280px !important;
}
</style>
